package com.example.mymvvmdemo.models.bind_email;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadActivity;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.ActivityBindEmailBinding;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.entity.FailEntity;
import com.example.mymvvmdemo.models.bind_email.entity.BindAccountEntity;
import com.example.mymvvmdemo.net.presenter.PostBodyPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.util.HashMap;

public class BindEmailActivity extends BaseLoadActivity<ActivityBindEmailBinding> implements View.OnClickListener, IView.PostBodyView {

    public static void startBindEmailActivity(Activity activity, int flag) {
        Intent intent = new Intent(activity, BindEmailActivity.class);
        intent.putExtra("flag", flag);
        activity.startActivity(intent);
    }

    private BindEmailViewModel viewModel;
    private PostBodyPresenter postBodyPresenter;

    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;


    @Override
    protected void showDialog() {
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(this, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(this);
    }

    @Override
    protected void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(this);
        }
    }

    @Override
    protected void initData() {
        viewModel = new ViewModelProvider(this).get(BindEmailViewModel.class);
        viewModel.flag = getIntent().getIntExtra("flag", BindEmailViewModel.TYPE_EMAIL);
        postBodyPresenter = new PostBodyPresenter(this);

        if (viewModel.flag == BindEmailViewModel.TYPE_PHONE) {
            initTitle(getString(R.string.user_info_phone));
            binding.etAccount.setHint(R.string.input_account_phone);
        } else {
            initTitle(getString(R.string.user_info_email));
            binding.etAccount.setHint(R.string.input_account_email);
        }


    }

    @Override
    protected void initListener() {
        binding.include.ivBack.setOnClickListener(this);
        binding.ivClose.setOnClickListener(this);
        binding.tvSend.setOnClickListener(this);
        binding.tvConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_close:
                binding.etAccount.setText("");
                break;
            case R.id.tv_send:
                sendSmsView();
                break;
            case R.id.tv_confirm:
                bindAccount();
                break;
            default:
                break;
        }
    }


    /***********************************Handler**************************************/
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (viewModel.currentNum < viewModel.allNum) {
                    viewModel.currentNum++;
                    int num = viewModel.allNum - viewModel.currentNum;
                    binding.tvSend.setText(num + getString(R.string.second));
                    uiHandler.sendEmptyMessageDelayed(1, 1000);
                } else {
                    viewModel.currentNum = 0;
                    binding.tvSend.setText(getString(R.string.send));
                    binding.tvSend.setEnabled(true);
                    binding.tvSend.setAlpha(1);
                }
            }

        }
    };

    /***********************************自定义方法**************************************/
    public void initTitle(String title) {
        binding.include.tvTitle.setVisibility(View.VISIBLE);
        binding.include.tvTitle.setText(title);
    }

    private void sendSmsView() {

        String account = binding.etAccount.getText().toString();

        if (StrUtils.isEmpty(account)) {
            if (viewModel.flag == BindEmailViewModel.TYPE_PHONE) {
                toast(R.string.input_account_phone, ToastUtils.TOA_W);
            } else {
                toast(R.string.input_account_email, ToastUtils.TOA_W);
            }
            return;
        }


        viewModel.currentNum = 0;
        binding.tvSend.setAlpha(0.5f);
        binding.tvSend.setEnabled(false);
        uiHandler.sendEmptyMessage(1);
        viewModel.account = account;
        if (viewModel.flag == BindEmailViewModel.TYPE_PHONE) {
            startLoadSendPhoneSms();
        } else {
            startLoadSendEmailSms();
        }

    }

    public void bindAccount() {

        String account = binding.etAccount.getText().toString();
        String sms = binding.etSms.getText().toString();

        if (StrUtils.isEmpty(account)) {

            if (viewModel.flag == BindEmailViewModel.TYPE_PHONE) {
                toast(R.string.input_account_phone, ToastUtils.TOA_W);
            } else {
                toast(R.string.input_account_email, ToastUtils.TOA_W);
            }

            return;
        }

        if (StrUtils.isEmpty(sms)) {
            toast(R.string.input_sms_code, ToastUtils.TOA_W);
            return;
        }

        viewModel.account = account;
        viewModel.sms = sms;

        if (viewModel.flag == BindEmailViewModel.TYPE_PHONE) {
            startLoadBindPhone();
        } else {
            startLoadSendBindEmail();
        }

    }

    public void startLoadSendEmailSms() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("email", "" + viewModel.account);
        postBodyPresenter.startLoadPostBody(UrlConstants.sendEmailCode, hashMap, UrlTypeConstants.sendEmailCode);
    }

    public void startLoadSendPhoneSms() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("mobile", "" + viewModel.account);
        postBodyPresenter.startLoadPostBody(UrlConstants.sendSmsCode, hashMap, UrlTypeConstants.sendSmsCode);
    }

    public void startLoadBindPhone() {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("mobile", "" + viewModel.account);
        hashMap.put("verify_code", "" + viewModel.sms);
        postBodyPresenter.startLoadPostBody(UrlConstants.bindMobile, hashMap, UrlTypeConstants.bindMobile);
    }

    public void startLoadSendBindEmail() {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("email", "" + viewModel.account);
        hashMap.put("verify_code", "" + viewModel.sms);
        postBodyPresenter.startLoadPostBody(UrlConstants.bindEmail, hashMap, UrlTypeConstants.bindEmail);
    }

    /***********************************数据请求回调**************************************/
    @Override
    public void loadPostBodySuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.sendEmailCode)) {
//            loadSendEmailCodeSuccess(result);
        }
        if (type.equals(UrlTypeConstants.sendSmsCode)) {
//            loadSendSmsCodeSuccess(result);
        }
        if (UrlTypeConstants.bindMobile.equals(type)) {
            loadBindPhoneSuccess(result, code);
        }
        if (UrlTypeConstants.bindEmail.equals(type)) {
            loadBindEmailSuccess(result, code);
        }
    }


    @Override
    public void loadPostBodyFail(String message, String type) {
        if (type.equals(UrlTypeConstants.sendEmailCode)) {
//            loadSendEmailCodeFail();
        }
        if (type.equals(UrlTypeConstants.sendSmsCode)) {
//            loadSendSmsCodeFail();
        }
        if (UrlTypeConstants.bindMobile.equals(type)) {
            loadBindPhoneFail();
        }
        if (UrlTypeConstants.bindEmail.equals(type)) {
            loadBindEmailFail();
        }
    }

    @Override
    public void loadPostBodyAccountError(int code) {

    }

    @Override
    public void loadPostBodyNetWorkError(String type) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    /***********************************处理请求后数据**************************************/
    private void loadBindEmailSuccess(String result, int code) {
        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }
        
        try {
            BindAccountEntity bindAccount = gson.fromJson(result, BindAccountEntity.class);
            toast(R.string.success, ToastUtils.TOA_S);
            finish();
        } catch (Exception e) {
            loadBindEmailFail();
        }

    }

    private void loadBindPhoneSuccess(String result, int code) {
        dismissDialog();
        if (code != 200) {
            FailEntity registerFailEntity = gson.fromJson(result, FailEntity.class);
            String message = registerFailEntity.getData().getMessage().getMessages().get(0);
            toast(message, ToastUtils.TOA_W);
            return;
        }

        try {
            BindAccountEntity bindAccount = gson.fromJson(result, BindAccountEntity.class);
            toast(R.string.success, ToastUtils.TOA_S);
            finish();
        } catch (Exception e) {
            loadBindPhoneFail();
        }

    }

    private void loadBindEmailFail() {
        dismissDialog();
        toast(R.string.fail, ToastUtils.TOA_W);
    }

    private void loadBindPhoneFail() {
        dismissDialog();
        toast(R.string.fail, ToastUtils.TOA_W);
    }

}